package com.jarich.morewore;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.jarich.morewore.model.MyOverlayItem;
import com.jarich.morewore.model.Plaats;
import com.jarich.morewore.model.TextDrawable;
import com.jarich.morewore.model.Weerbericht;

public class MapActivity extends Activity implements android.widget.PopupMenu.OnMenuItemClickListener{
	
	GoogleMap mMap;
	Weerbericht w;
	LocationManager locationManager;
	LocationListener locationListener;
	boolean gpsEnabled = false;
	double[] coords = new double[4];
	ArrayList<Marker> weatherMarkers = new ArrayList<Marker>();
	Marker locationMarker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
//		handleIntent(getIntent());
		setUpMapIfNeeded();
		mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
		mMap.setOnCameraChangeListener(new CameraChangedListener());
		
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		
	     // Define a listener that responds to location updates
	        locationListener = new LocationListener() {
	            public void onLocationChanged(Location location) {
	            	if(locationMarker == null)
	            	{
	            		locationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("You're location"));
	            		mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()),7.0f));
	            		displayBiggestCities();
	            	}
	            	
	              // Called when a new location is found by the network location provider.	            	
	            	locationMarker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
	            	locationMarker.setVisible(true);
	            }

	            public void onStatusChanged(String provider, int status, Bundle extras) {}

	            public void onProviderEnabled(String provider) {
	            	if(provider.equals("gps"))
	            	{
	            		gpsEnabled = true;
	            	}
	            }

	            public void onProviderDisabled(String provider) {
	            	System.out.println(provider + " is disabled");
	            	if(provider.equals("gps"))
	            	{
	            		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

	            		AlertDialog.Builder dialog = new AlertDialog.Builder(MapActivity.this);
	            		dialog.setTitle("GPS uitgeschakeld..");
	            		dialog.setMessage("Voor betere plaatsbepaling wordt aangeraden uw GPS in te schakelen indien mogelijk.");
	            		//TODO weggehaald omdat het irritant is////// dialog.show();
	            	}
	            }
	          };

	        // Register the listener with the Location Manager to receive location updates
	        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

	        displayBiggestCities();
	}
	
	class CameraChangedListener implements GoogleMap.OnCameraChangeListener
	{

		@Override
		public void onCameraChange(CameraPosition position) {
			displayBiggestCities();
		}
	}
   
   class TouchEventOverlay extends Overlay{
	    @Override

	    public boolean onTouchEvent(MotionEvent event, MapView mapview){

	        if (event.getAction() == MotionEvent.ACTION_UP){
	        	displayBiggestCities();
	            //Nieuwe lijst met steden ophalen en die weergeven
	        }
	        return false;
	    }
	}
   
   public void displayBiggestCities()
   {
	   LatLngBounds visibleBounds = mMap.getProjection().getVisibleRegion().latLngBounds;
	   System.out.println(visibleBounds.toString());
	   PlaceMarkersTask pmt = new PlaceMarkersTask();
	   coords[0] = visibleBounds.southwest.latitude;
	   coords[1] = visibleBounds.northeast.latitude;
	   coords[2] = visibleBounds.southwest.longitude;
	   coords[3] = visibleBounds.northeast.longitude;
	   pmt.execute();
   }
     
   /**
    * Depricated..
    *
    */
   private class GetWOEIDTask extends AsyncTask<Void, Void, Void> {
   	int woeid;
   	@Override
       protected void onPostExecute(Void param) {
           System.out.println(woeid);
       }

		@Override
		protected Void doInBackground(Void... params) {
			woeid = w.getWOEID("Nijverdal");
			System.out.println(woeid);
			return null;
		}
   }
   
   private class PlaceMarkersTask extends AsyncTask<Void, Void, ArrayList<MarkerData>> {
	   	@Override
	       protected void onPostExecute(ArrayList<MarkerData> markerData) {
	    	   if(markerData != null && markerData.size() > 0)
	    	   {
	    		   for(Marker m : weatherMarkers)
	    		   {
	    			   m.remove();
	    		   }
	    		   weatherMarkers.clear();
	    		   for(MarkerData md : markerData)
	    		   {
	    			   if(md.image != null)
	    				   weatherMarkers.add(mMap.addMarker(new MarkerOptions().position(md.latlng).title(md.naam).icon(BitmapDescriptorFactory.fromBitmap(md.image))));
	    		   }
	    	   }
	       }

			@Override
			protected ArrayList<MarkerData> doInBackground(Void... params) {
				//lat1, lat2, lon1, lon2
				ArrayList<Plaats> plaatsenLijst = Connector.getTheCityList(coords[0], coords[1], coords[2], coords[3]);
				ArrayList<MarkerData> markerData = new ArrayList<MarkerData>();
				if(plaatsenLijst.size() > 0)
				{
					Bitmap image;
					for(int i = 0;i<plaatsenLijst.size() && i < 5; i++)
					{
						Plaats p = plaatsenLijst.get(i);
						image = Weerbericht.getBitmapIcon(Weerbericht.getStaticWOEID(p.getPlaatsNaam()), getBaseContext());
						markerData.add(new MarkerData(new LatLng(p.getLon(),p.getLat()),p.getPlaatsNaam(),image));
					}
				}
				return markerData;
			}
	   }  
   
   public Bitmap textOnBitmap(Bitmap b, String text) {
	   Canvas c = new Canvas(b);
	   Paint p = new Paint();

	   p.setColor(Color.WHITE);
	   c.drawText(text, -30, -20, p);

	   return b; 
   }
   
   private class MarkerData
   {
	   public LatLng latlng;
	   public String naam;
	   public Bitmap image;
	   
	   public MarkerData(LatLng l, String n, Bitmap i)
	   {
		   latlng = l;
		   naam = n;
		   image = i;
	   }
   }
   
   
   /**
    * Deprecated.. 
    */
   private class GetPlaatsTask extends AsyncTask<Void, Void, ArrayList<MyOverlayItem>> {
   	@Override
       protected void onPostExecute(ArrayList<MyOverlayItem> overlayList) {
    	   if(overlayList != null);
    		   //addNewOverlays(overlayList);
       }

		@Override
		protected ArrayList<MyOverlayItem> doInBackground(Void... params) {
			//lat1, lat2, lon1, lon2
			System.out.println(params);
			ArrayList<Plaats> plaatsenLijst = Connector.getTheCityList(coords[0], coords[1], coords[2], coords[3]);
			System.out.println("klaar denkik?");
			if(plaatsenLijst.size() > 0)
			{
				ArrayList<MyOverlayItem> overlays = new ArrayList<MyOverlayItem>();
				Drawable drawable;// = MeerWeerActivity.this.getResources().getDrawable(R.drawable.androidmarker);
				for(int i = 0;i<plaatsenLijst.size() && i < 5; i++)
				{
					drawable = Weerbericht.getIcon(Weerbericht.getStaticWOEID(plaatsenLijst.get(i).getPlaatsNaam()), getBaseContext());
					MyOverlayItem moi = new MyOverlayItem(drawable, MapActivity.this, 2+i);
					moi.plaatsNaam = plaatsenLijst.get(i).getPlaatsNaam();
					GeoPoint point = new GeoPoint((int)(plaatsenLijst.get(i).getLon()*1E6),(int)(plaatsenLijst.get(i).getLat()*1E6));
					OverlayItem overlayitem = new OverlayItem(point, plaatsenLijst.get(i).getPlaatsNaam(), "kutweer hiero");

	        		moi.addOverlay(overlayitem);
	        		overlays.add(moi);
				}
				return overlays;
			}
			return null;
		}
   }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            System.out.println("DAHDAHDAHDAHDAH");
        }
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.search:
			//onSearchRequested();
			Intent intent = new Intent(this, Search.class);
		    startActivity(intent);
			return true;
//		case R.id.help:
//			showHelp();
//			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void setUpMapIfNeeded() {
	    // Do a null check to confirm that we have not already instantiated the map.
	    if (mMap == null) {
	        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
	                            .getMap();
	        // Check if we were successful in obtaining the map.
	        if (mMap != null) {
	            // The Map is verified. It is now safe to manipulate the map.

	        }
	    }
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		System.out.println("klik");
		if(item.getItemId() == R.id.search){
			Toast.makeText(getApplicationContext(), "Klik", Toast.LENGTH_SHORT).show();
		}
		return false;
	}

}
